import PythonMagick
from dxfwrite import DXFEngine as dxf

def getPixel(image, x, y):
    'returns 16-bit integers (0-65535)'
    color = image.pixelColor(x, y)
    return (color.redQuantum(), color.greenQuantum(), color.blueQuantum())

    
d = dxf.drawing("c:\\Users\\Matt\Documents\\Autodesk\\cut.dxf")

mm = (93, 70)
tip = 0.5
newsize = (round(mm[0] / tip), round(mm[1] / tip))

img = PythonMagick.Image("d:\\tmp\\c1.gif")

img.sample("!%sx%s" % (newsize[0], newsize[1]))

img.write("d:\\tmp\\c1-out.gif")


for x in range(0, newsize[0]):
	cut_start = 0
	cut_end = 0
	cutting = False
	for y in range(0, newsize[1]) :
		color = getPixel(img, x, newsize[1] - y)
		if color[0] > 32767 : # white, needs cutting
			if cutting : 
				# keep cutting
				cut_end = y
			else : 
				# start cutting
				cut_start = cut_end = y
			cutting = True
		else : # black, stop cutting
			if cutting :
				# write out the cut
				d.add(dxf.line((x / tip, cut_start / tip), (x / tip, cut_end / tip)))
			else :
				# keep going
				cut_start = cut_end = y
			cutting = False
	if cutting :
		d.add(dxf.line((x / tip, cut_start / tip), (x / tip, cut_end / tip)))
			

for y in range(0, newsize[1]):
	cut_start = 0
	cut_end = 0
	cutting = True
	for x in range(0, newsize[0]) :
		color = getPixel(img, x, newsize[1] - y)
		if color[0] > 32767 :
			if cutting:
				cut_end = x
			else :
				cut_start = cut_end = x
			cutting = True
		else :
			if cutting :
				d.add(dxf.line((cut_start / tip,y / tip), (cut_end / tip, y / tip)))
				cutting = False
			else :
				cut_start = cut_end = x
			cutting = False
				
	if cutting :
		d.add(dxf.line((cut_start / tip,y / tip), (cut_end / tip, y / tip)))
	
d.save()

